package k8s

import (
	"context"

	corev1 "k8s.io/api/core/v1"
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	core "k8s.io/client-go/kubernetes/typed/core/v1"
)

func NewPods(c *kubernetes.Clientset) *Pods {
	return &Pods{
		core: c.CoreV1(),
	}
}

type Pods struct {
	core core.CoreV1Interface
}

// 获取Pod列表
func (s *Pods) GetPods(ctx context.Context, namespace string, req *v1.ListOptions) (*corev1.PodList, error) {
	return s.core.Pods(namespace).List(ctx, *req)
}

// 获取Pod详情
func (s *Pods) GetPodDetails(ctx context.Context, namespace, name string) (*corev1.Pod, error) {
	return s.core.Pods(namespace).Get(ctx, name, v1.GetOptions{})
}

// 删除Pod
func (s *Pods) DeletePod(ctx context.Context, namespace, name string) error {
	return s.core.Pods(namespace).Delete(ctx, name, v1.DeleteOptions{})
}

// 创建Pod
func (s *Pods) CreatePod(ctx context.Context, namespace string, pod *corev1.Pod) (*corev1.Pod, error) {
	return s.core.Pods(namespace).Create(ctx, pod, v1.CreateOptions{})
}

// 更新Pod
func (s *Pods) UpdatePod(ctx context.Context, namespace string, pod *corev1.Pod) (*corev1.Pod, error) {
	return s.core.Pods(namespace).Update(ctx, pod, v1.UpdateOptions{})
}

// 获取Pod日志
func (s *Pods) GetPodLogs(ctx context.Context, namespace, name string, req *corev1.PodLogOptions) (string, error) {
	logInfo, err := s.core.Pods(namespace).GetLogs(name, req).Do(ctx).Raw()
	if err != nil {
		return "", err
	}

	return string(logInfo), nil
}
